package com.zjeav.lingjiao.ui.book;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dalimao.corelibrary.pullrefresh.BGANormalRefreshViewHolder;
import com.dalimao.corelibrary.pullrefresh.BGARefreshLayout;
import com.dalimao.corelibrary.pullrefresh.PowerfulRecyclerView;
import com.dalimao.corelibrary.pullrefresh.TipView;
import com.dalimao.corelibrary.utils.NetWorkUtils;
import com.zjeav.lingjiao.R;
import com.zjeav.lingjiao.base.adapter.BookAdapter;
import com.zjeav.lingjiao.base.baseBean.BaseActivity;
import com.zjeav.lingjiao.base.baseBean.Book;
import com.zjeav.lingjiao.base.baseBean.Province;
import com.zjeav.lingjiao.base.request.MallBookRequest;
import com.zjeav.lingjiao.base.response.SubjectResponse;
import com.zjeav.lingjiao.base.utils.UIUtils;
import com.zjeav.lingjiao.ui.presenter.BookPresenter;

import java.util.ArrayList;

public class BookMarketActivity extends BaseActivity implements View.OnClickListener, MallBookContract.View,
        BGARefreshLayout.BGARefreshLayoutDelegate, BaseQuickAdapter.RequestLoadMoreListener {
    private TextView grade_txt, subject_txt;

    private TipView tipView;
    private BGARefreshLayout mRefreshLayout;
    private PowerfulRecyclerView mBooks;

    private ImageView back_img;
    private BookAdapter adapter;
    private ArrayList<Book> books = new ArrayList<>();
    private int index = 1;
    private int size = 10;
    private boolean ispull = true; //是否是下拉刷新
    private BookPresenter bookPresenter;
    private String keyword;
    private String name;

    private ArrayList<String> mHobbyNameList;//用于选择器显示
    private OptionsPickerView mHobbyPickerView;//年级选择器

    private ArrayList<String> msubNameList;//用于学科显示
    private OptionsPickerView msubPickerView;//学科选择器
    private ArrayList<String> msubIDList;//用于学科ID显示
    String strsubjectid = ""; //学科
    String strgrade = "";//年级

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.bookmarketlayout);
        init();
    }

    private void init() {
        keyword = getIntent().getStringExtra("keyword");
        strsubjectid = String.valueOf(getIntent().getIntExtra("subjectid", 1));
        name = getIntent().getExtras().getString("name","");
        grade_txt = findViewById(R.id.grade_txt);
        back_img = findViewById(R.id.back_img);
        tipView = findViewById(R.id.tip_view);
        mRefreshLayout = findViewById(R.id.refresh_layout);
        mBooks = findViewById(R.id.rv_books);
        subject_txt = findViewById(R.id.subject_txt);
        subject_txt.setText(name);

        mHobbyNameList = new ArrayList<>();
        msubNameList = new ArrayList<>();
        msubIDList = new ArrayList<>();

        //变化的布局
        grade_txt.setOnClickListener(this);
        subject_txt.setOnClickListener(this);
        back_img.setOnClickListener(this);
        bookPresenter = new BookPresenter(this);

        adapter = new BookAdapter(this,1);
        adapter.setEnableLoadMore(true);
        adapter.setOnLoadMoreListener(this,mBooks);
        mRefreshLayout.setDelegate(this);
        mBooks.setLayoutManager(new GridLayoutManager(this, 3));
        // 设置下拉刷新和上拉加载更多的风格     参数1：应用程序上下文，参数2：是否具有上拉加载更多功能
        BGANormalRefreshViewHolder refreshViewHolder = new BGANormalRefreshViewHolder(this, false);
        // 设置下拉刷新
        refreshViewHolder.setRefreshViewBackgroundColorRes(R.color.color_F3F5F4);//背景色
        refreshViewHolder.setPullDownRefreshText(UIUtils.getString(R.string.refresh_pull_down_text));//下拉的提示文字
        refreshViewHolder.setReleaseRefreshText(UIUtils.getString(R.string.refresh_release_text));//松开的提示文字
        refreshViewHolder.setRefreshingText(UIUtils.getString(R.string.refresh_ing_text));//刷新中的提示文字
        // 设置下拉刷新和上拉加载更多的风格
        mRefreshLayout.setRefreshViewHolder(refreshViewHolder);
        mRefreshLayout.shouldHandleRecyclerViewLoadingMore(mBooks);
        mBooks.setAdapter(adapter);

        bookPresenter.getFiltrateBooks(new MallBookRequest(index, size, strsubjectid));
        bookPresenter.getGrades();
        bookPresenter.getSubjects();

        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Book book = (Book) adapter.getItem(position);
                Log.d("id", books.get(position).getId() + "");
                Intent intent = new Intent(BookMarketActivity.this, BookDetialActivity.class);
                intent.putExtra("id", book.getId());
                intent.putExtra("isbuy", true);
                startActivity(intent);
            }
        });
    }

    //初始化年级选择器
    private void initHobbyOptionPicker() {
        mHobbyPickerView = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                strgrade = mHobbyNameList.get(options1);
                grade_txt.setText(strgrade);

                index = 1;
                books.clear();

                MallBookRequest mallBookRequest = null;
                if ("全部年级".equals(strgrade)){
                    mallBookRequest = new MallBookRequest(index, size, strsubjectid);
                }else {
                    mallBookRequest = new MallBookRequest(index, size, strsubjectid, strgrade);
                }

                bookPresenter.getFiltrateBooks(mallBookRequest);

            }
        })
                .setDecorView((RelativeLayout)findViewById(R.id.activity_rootview))//必须是RelativeLayout，不设置setDecorView的话，底部虚拟导航栏会显示在弹出的选择器区域
                .setTitleText("选择年级")//标题文字
                .setTitleSize(20)//标题文字大小
                .setTitleColor(getResources().getColor(R.color.pickerview_title_text_color))//标题文字颜色
                .setCancelText("取消")//取消按钮文字
                .setCancelColor(getResources().getColor(R.color.pickerview_cancel_text_color))//取消按钮文字颜色
                .setSubmitText("确定")//确认按钮文字
                .setSubmitColor(getResources().getColor(R.color.pickerview_submit_text_color))//确定按钮文字颜色
                .setContentTextSize(20)//滚轮文字大小
                .setTextColorCenter(getResources().getColor(R.color.pickerview_center_text_color))//设置选中文本的颜色值
                .setLineSpacingMultiplier(1.8f)//行间距
                .setDividerColor(getResources().getColor(R.color.pickerview_divider_color))//设置分割线的颜色
                .setSelectOptions(0)//设置选择的值
                .build();

        mHobbyPickerView.setPicker(mHobbyNameList);//添加数据
    }

    //初始化学科选择器
    private void initsubOptionPicker() {
        msubPickerView = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                strsubjectid = msubIDList.get(options1);
                String strsubname = msubNameList.get(options1);
                subject_txt.setText(strsubname);

                index = 1;
                books.clear();

                MallBookRequest mallBookRequest = null;
                if ("全部年级".equals(strgrade)){
                    mallBookRequest = new MallBookRequest(index, size, strsubjectid);
                }else {
                    mallBookRequest = new MallBookRequest(index, size, strsubjectid, strgrade);
                }

                bookPresenter.getFiltrateBooks(mallBookRequest);

            }
        })
                .setDecorView((RelativeLayout)findViewById(R.id.activity_rootview))//必须是RelativeLayout，不设置setDecorView的话，底部虚拟导航栏会显示在弹出的选择器区域
                .setTitleText("选择学科")//标题文字
                .setTitleSize(20)//标题文字大小
                .setTitleColor(getResources().getColor(R.color.pickerview_title_text_color))//标题文字颜色
                .setCancelText("取消")//取消按钮文字
                .setCancelColor(getResources().getColor(R.color.pickerview_cancel_text_color))//取消按钮文字颜色
                .setSubmitText("确定")//确认按钮文字
                .setSubmitColor(getResources().getColor(R.color.pickerview_submit_text_color))//确定按钮文字颜色
                .setContentTextSize(20)//滚轮文字大小
                .setTextColorCenter(getResources().getColor(R.color.pickerview_center_text_color))//设置选中文本的颜色值
                .setLineSpacingMultiplier(1.8f)//行间距
                .setDividerColor(getResources().getColor(R.color.pickerview_divider_color))//设置分割线的颜色
                .setSelectOptions(0)//设置选择的值
                .build();

        msubPickerView.setPicker(msubNameList);//添加数据
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.grade_txt:
                grade_txt.setBackground(getResources().getDrawable(R.drawable.bg_border_top));
                grade_txt.setTextColor(getResources().getColor(R.color.black));
                Drawable drawablegrent = getResources().getDrawable(R.mipmap.triangle_blue);
                drawablegrent.setBounds(0, 0, drawablegrent.getMinimumWidth(), drawablegrent.getMinimumHeight());
                grade_txt.setCompoundDrawables(null, null, drawablegrent, null);

                subject_txt.setBackground(getResources().getDrawable(R.drawable.bg_border));
                subject_txt.setTextColor(getResources().getColor(R.color.white));
                Drawable drawableright = getResources().getDrawable(R.mipmap.triangle_white);
                drawableright.setBounds(0, 0, drawableright.getMinimumWidth(), drawableright.getMinimumHeight());
                subject_txt.setCompoundDrawables(null, null, drawableright, null);

                initHobbyOptionPicker();
                mHobbyPickerView.show();

                break;
            case R.id.subject_txt:
                subject_txt.setBackground(getResources().getDrawable(R.drawable.bg_border_top));
                subject_txt.setTextColor(getResources().getColor(R.color.black));
                Drawable drawablesub = getResources().getDrawable(R.mipmap.triangle_blue);
                drawablesub.setBounds(0, 0, drawablesub.getMinimumWidth(), drawablesub.getMinimumHeight());
                subject_txt.setCompoundDrawables(null, null, drawablesub, null);

                grade_txt.setBackground(getResources().getDrawable(R.drawable.bg_border));
                grade_txt.setTextColor(getResources().getColor(R.color.white));
                Drawable drawablegent = getResources().getDrawable(R.mipmap.triangle_white);
                drawablegent.setBounds(0, 0, drawablegent.getMinimumWidth(), drawablegent.getMinimumHeight());
                grade_txt.setCompoundDrawables(null, null, drawablegent, null);

                initsubOptionPicker();
                msubPickerView.show();

                break;
            case R.id.back_img:
                finish();
                break;
            default:
                break;
        }
    }

    @Override
    public void showMallBooks(ArrayList<Book> list) {
        if (ispull) {
            tipView.show("加载数据成功");
        }

        if (list.size()<= 0) {
            adapter.loadMoreEnd();
            mRefreshLayout.endRefreshing();// 加载完毕后在 UI 线程结束下拉刷新
        }
        mRefreshLayout.endRefreshing();// 加载完毕后在 UI 线程结束下拉刷新

        books.addAll(list);
        adapter.replaceData(this.books);
    }

    @Override
    public void getGrades(ArrayList<SubjectResponse> list) {
        if (ispull) {
            tipView.show("加载数据成功");
        }

        if (list.size()<= 0) {
            adapter.loadMoreEnd();
            return;
        }
        mRefreshLayout.endRefreshing();// 加载完毕后在 UI 线程结束下拉刷新

        mHobbyNameList.add("全部年级");
        for (int i = 0; i < list.size(); i++) {
            mHobbyNameList.add(list.get(i).getName());
        }
    }

    @Override
    public void getSubjects(ArrayList<SubjectResponse> list) {

        if (ispull) {
            tipView.show("加载数据成功");
        }

        if (list.size()<= 0) {
            adapter.loadMoreEnd();
            return;
        }
        mRefreshLayout.endRefreshing();// 加载完毕后在 UI 线程结束下拉刷新

        msubIDList.add("");
        msubNameList.add("全部学科");

        for (int i = 0; i < list.size(); i++) {
            msubIDList.add(String.valueOf(list.get(i).getId()));
            msubNameList.add(list.get(i).getName());
        }
    }

    @Override
    public void showError(Throwable throwable) {
        if (ispull) {
            tipView.show("数据加载异常");
        }
        mRefreshLayout.endRefreshing();// 加载完毕后在 UI 线程结束下拉刷新
    }

    @Override
    public void showRegions(ArrayList<Province> province) {

    }


    /**
     * 下拉刷新
     *
     * @param refreshLayout
     */
    @Override
    public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
        ispull =true;
        if (!NetWorkUtils.isNetworkAvailable(this)) {
            //网络不可用弹出提示
            tipView.show();
            if (mRefreshLayout.getCurrentRefreshStatus() == BGARefreshLayout.RefreshStatus.REFRESHING) {
                mRefreshLayout.endRefreshing();
            }
            return;
        }

        index = 1;
        books.clear();
        bookPresenter.getFiltrateBooks(new MallBookRequest(index, size, strsubjectid));
    }

    @Override
    public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
        return false;
    }

    /**
     * 上拉加载更多
     */
    @Override
    public void onLoadMoreRequested() {
        ispull = false;
        index++;
        bookPresenter.getFiltrateBooks(new MallBookRequest(index, size, strsubjectid));
        adapter.loadMoreComplete();
    }
}
